package com.hwzn.module.admin.filter;

import static com.hwzn.module.core.enums.ErrorCodeConstants.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.alibaba.fastjson.JSON;
import com.hwzn.module.admin.service.UserService;
import com.hwzn.module.core.dos.UserDO;
import com.hwzn.module.core.exception.ErrorCode;
import com.hwzn.module.core.pojo.Result;
import com.hwzn.module.core.utils.JwtTokenUtil;

/**
 * jwt filter
 *
 * @author jiaobo
 * @date Created in 2024/5/15 16:57
 * @company hw
 **/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        if ("/admin/login".equals(request.getRequestURI()) || "/admin/register".equals(request.getRequestURI()) ) {
            filterChain.doFilter(request, response);
        }else {
            if ("/login".equals(request.getRequestURI())) {
                writeJson(response,AUTH_LOGIN_BAD_CREDENTIALS);
                return;
            }
            // get token
            String token = request.getHeader("token");
            if (!StringUtils.hasText(token)) {
                // pass
                writeJson(response,AUTH_TOKEN_ERROR);
                return;
            }

            // analysis token
            if (JwtTokenUtil.checkJWT(token) == null) {
                writeJson(response,AUTH_TOKEN_ERROR);
                return;
            }

            // check timeout
            if (JwtTokenUtil.isExpiration(token)) {
                writeJson(response,AUTH_TOKEN_EXPIRED);
                return;
            }

            // get userId
            Long userId = Long.valueOf(JwtTokenUtil.getUserId(token));

            //get user
            UserDO userDO = userService.getUserById(userId);

            //get auth
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(userDO, null, userDO.getAuthorities());

            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            // pass
            filterChain.doFilter(request, response);
        }

    }

    private void writeJson(HttpServletResponse response, ErrorCode msg) throws IOException {
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        Result commonResult = new Result();
        commonResult.setCode(msg.getCode());
        commonResult.setMsg(msg.getMsg());
        String s = JSON.toJSONString(commonResult);
        response.getWriter().println(s);
    }
}
